package com.buildings.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.buildings.R;
import com.buildings.view.NumberProgressBar;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by songwei on 2017/1/6.
 */

public class UpdateManager {
    private Context mContext; //上下文

    private String apkUrl = ""; //apk下载地址
    private static final String savePath = "/sdcard/updateAPK/"; //apk保存到SD卡的路径
    private static final String saveFileName = savePath + "yyb.apk"; //完整路径名

    private NumberProgressBar mProgress; //下载进度条控件
    private static final int DOWNLOADING = 1; //表示正在下载
    private static final int DOWNLOADED = 2; //下载完毕
    private static final int DOWNLOAD_FAILED = 3; //下载失败
    private int progress; //下载进度
    private boolean cancelFlag = false; //取消下载标志位

    private String serverVersion = "1.0"; //从服务器获取的版本号
    private String updateDescription = "检测到新版本，立即更新吗?\n建议在wifi条件下更新"; //更新内容描述信息
    private boolean mForceUpdate = false; //是否强制更新


    private AlertDialog alertDialog1, alertDialog2; //表示提示对话框、进度条对话框


    /**
     * 构造函数
     */
    public UpdateManager(Context context) {
        this.mContext = context;

    }

    public void setUpdateParms(String path, String version, String content, boolean forceUpdate) {
        this.apkUrl = path;
        this.serverVersion = version;
        this.updateDescription = content;
        this.mForceUpdate = forceUpdate;


//        if (!apkUrl.equals("") && !serverVersion.equals("")) {
//
//            showNoticeDialog();
//        }

    }

    /**
     * 显示进度条对话框
     */
    public void showDownloadDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (NumberProgressBar) v.findViewById(R.id.update_progress);
        Button button = (Button) v.findViewById(R.id.button);
        dialog.setView(v);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog2.dismiss();
            }
        });
        alertDialog2 = dialog.create();
        alertDialog2.setCancelable(false);
        alertDialog2.show();

        //下载apk
        downloadAPK();
    }

    /**
     * 下载apk的线程
     */
    public void downloadAPK() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                try {
//                    URL url = new URL(apkUrl);
//                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    conn.connect();
//
//                    int length = conn.getContentLength();
//
//                    InputStream is = conn.getInputStream();
//
//
//                    File file = new File(savePath);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                    String apkFile = saveFileName;
//                    File ApkFile = new File(apkFile);
//                    FileOutputStream fos = new FileOutputStream(ApkFile);
//
//                    int count = 0;
//                    byte buf[] = new byte[1024];
//
//                    do {
//                        int numread = is.read(buf);
//
//                        count += numread;
//
//                        progress = (int) (((float) count / length) * 100);
//
//                        //更新进度
//                        mHandler.sendEmptyMessage(DOWNLOADING);
//                        if (numread <= 0) {
//                            //下载完成通知安装
//                            mHandler.sendEmptyMessage(DOWNLOADED);
//                            break;
//                        }
//                        fos.write(buf, 0, numread);
//                    } while (!cancelFlag); //点击取消就停止下载.
//
//                    fos.close();
//                    is.close();
//                } catch (Exception e) {
//
//                    alertDialog2.dismiss();
//
//                    mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
//                    e.printStackTrace();
//                }
//            }
//        }).start();

        Request request = new Request.Builder().url(apkUrl).build();
//        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        //信任所有服务器地址
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                //设置为true
                return true;
            }
        });
        //创建管理器
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            //为OkHttpClient设置sslSocketFactory
            builder.sslSocketFactory(sslContext.getSocketFactory());

        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpClient okHttpClient = builder.build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                alertDialog2.dismiss();
                mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                // 储存下载文件的目录
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        progress = (int) (sum * 1.0f / total *100 );
                        // 下载中
                        //更新进度
                        mHandler.sendEmptyMessage(DOWNLOADING);
                    }
                    fos.flush();

                    //下载完成通知安装
                    mHandler.sendEmptyMessage(DOWNLOADED);
                } catch (Exception e) {
                    alertDialog2.dismiss();
                    mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });


    }

    /**
     * 更新UI的handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case DOWNLOADING:
                    if(progress > 30){
                        String a = "";
                    }
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOADED:
                    if (alertDialog2 != null)
                        alertDialog2.dismiss();
                    installAPK();
                    break;
                case DOWNLOAD_FAILED:
                    CustomToast.showToast(mContext, "更新失败，请重试！");
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 下载完成后自动安装apk
     */
//    public void installAPK() {
//        File apkFile = new File(saveFileName);
//        if (!apkFile.exists()) {
//            return;
//        }
////      Intent intent = new Intent(Intent.ACTION_VIEW);
////判断是否是AndroidN以及更高的版本
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
////            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
////            Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
////            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
////        } else {
////            intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
////            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////        }
////        mContext.startActivity(intent);
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
//        mContext.startActivity(intent);
//    }

    private  void installAPK() {
        File apkFile = new File(saveFileName);
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.buildings.fileprovider", apkFile); //与manifest中定义的provider中的authorities="cn.wlantv.kznk.fileprovider"保持一致
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

}
